package com.kinon.ceshiaccount.util;

import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.kinon.ceshiaccount.sunmi.SunmiSdkManage;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lhqq on 2018-02-27.
 */

public class ImgDonwloads {

    private static String filePath;
    private static Bitmap mBitmap;
    private static String mFileName = "caizhengting.png";
    private static String mSaveMessage;
    private static Context context;
    private static Handler messageHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            mSaveDialog.dismiss();
//            Log.d(TAG, mSaveMessage);
        }
    };
    private static Runnable saveFileRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                byte[] data = getImage(filePath);
                if (data != null) {
                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
                } else {
                    Log.e("lh", "Image error!");
                }

                saveFile(mBitmap, mFileName);
                mSaveMessage = "图片保存成功！";
            } catch (IOException e) {
                mSaveMessage = "图片保存失败！";
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            messageHandler.sendMessage(messageHandler.obtainMessage());
        }

    };

    public static void donwloadImg(Context contexts, String filePaths) {
        context = contexts;
        filePath = filePaths;
//        mSaveDialog = ProgressDialog.show(context, "保存图片", "图片正在保存中，请稍等...", true);
        Log.e("lh", "图片正在保存中，请稍等...");
        new Thread(saveFileRunnable).start();
    }

    public static byte[] getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return readStream(inStream);
        }
        return null;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    public static void saveFile(Bitmap bm, String fileName) throws IOException {
        if (ContextCompat.checkSelfPermission(context, "android.permission.WRITE_EXTERNAL_STORAGE")
                != PackageManager.PERMISSION_GRANTED) {
            Log.e("lh", "无文件编辑权限");

        }
//        File dirFile = new File(Environment.getExternalStorageDirectory().getPath()+"/dcim");
//        if(!dirFile.exists()){
//            dirFile.mkdir();
//        }
//        fileName = UUID.randomUUID().toString()+".jpg";
//        File jia=new File(Environment.getExternalStorageDirectory().getPath() +"/DCIM/VIMI8");
        File jia = new File(Environment.getExternalStorageDirectory().getPath() + "/dcim");
        if (!jia.exists()) {   //判断文件夹是否存在，不存在则创建
            jia.mkdirs();
        }
        String imgPath = jia + "/" + fileName;
        File myCaptureFile = new File(imgPath);
        if (myCaptureFile.exists()) {
            myCaptureFile.delete();
        }
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

//        long fileId = SharedPreferencesUtil.getLong(context,
//                WELCOME_IMG_ID);
//        //判断文件是否存在
//        if(fileId!=-1L)
//            SunmiSdkManage.getInstance().checkImg(context,
//                        fileId, WELCOME_IMG_ID);
//        SharedPreferencesUtil.put(context, SunmiImgPath.WELCOME_IMG_ID, fileId);

        SunmiSdkManage.getInstance().setWelcomeImg(imgPath);
//        SunmiSdkManage.getInstance().showPicture(fileId);

        //把图片保存后声明这个广播事件通知系统相册有新图片到来
//        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri uri = Uri.fromFile(myCaptureFile);
//        intent.setData(uri);
//        context.sendBroadcast(intent);
    }


}
